<template>
	<el-select v-model="inputValue" v-bind="selectConfig" :loading="selectLoading">
		<el-option v-for="(item, index) in userOptions" :key="index" :label="item.userName" :value="item.id"></el-option>
	</el-select>
</template>

<script>
import { getUserList, userDetail } from '@/api/system/tbSysUser';
export default {
	name: 'swUserSelect',
	props: {
		value: { type: String, default: '' }
	},
	data() {
		return {
			inputValue: this.value,
			selectLoading: false,
			selectConfig: {
				remote: true,
				clearable: true,
				filterable: true,
				reserveKeyword: true,
				defaultFirstOption: true,
				placeholder: '请输入用户关键字',
				remoteMethod: this.handleRemoteMethod
			},
			userOptions: []
		};
	},
	watch: {
		value(val) {
			this.inputValue = val;
		},
		inputValue(val) {
			this.$emit('input', val);
			if (!val) {
				this.userOptions = [];
			} else {
				this.queryUserById(val);
			}
		}
	},
	methods: {
		//获取用户列表
		async getUserListData(data) {
			let params = { page: 1, limit: 20, ...data };
			let result = await getUserList(params).then((res) => res.data);
			this.selectLoading = false;
			if (result.code === '0') {
				return Promise.resolve(result.data || []);
			} else {
				return Promise.resolve([]);
			}
		},

		//获取用户详情
		async getUserDetailData(id) {
			let result = await userDetail(id).then((res) => res.data);
			this.selectLoading = false;
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				return Promise.resolve(datas);
			} else {
				return Promise.resolve({});
			}
		},

		//关键字远程搜索
		handleRemoteMethod(query) {
			let params = { userName: query };
			this.selectLoading = true;
			this.getUserListData(params).then((res) => {
				this.userOptions = res;
			});
		},

		//获取当前用户 - 根据用户ID
		queryUserById(id) {
			this.selectLoading = true;
			this.getUserDetailData(id).then((res) => {
				this.userOptions = [res];
			});
		}
	}
};
</script>

<style lang="scss" scoped></style>
